<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="cookie与session," />










<meta name="description" content="django中的cookie和session cookie（储存在用户本地终端上的数据）Cookie，有时也用其复数形式 Cookies，指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据（通常经过加密）。定义于 RFC2109 和 2965 中的都已废弃，最新取代的规范是 RFC6265 [1]  。（可以叫做浏览器缓存）   session（计算机语言）:在计算">
<meta name="keywords" content="cookie与session">
<meta property="og:type" content="article">
<meta property="og:title" content="Django之Cookie和Session">
<meta property="og:url" content="http://yoursite.com/2018/05/25/Django之Cookie和Session/index.html">
<meta property="og:site_name" content="Mr. Lee&#39;s blog">
<meta property="og:description" content="django中的cookie和session cookie（储存在用户本地终端上的数据）Cookie，有时也用其复数形式 Cookies，指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据（通常经过加密）。定义于 RFC2109 和 2965 中的都已废弃，最新取代的规范是 RFC6265 [1]  。（可以叫做浏览器缓存）   session（计算机语言）:在计算">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-05-25T14:44:19.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Django之Cookie和Session">
<meta name="twitter:description" content="django中的cookie和session cookie（储存在用户本地终端上的数据）Cookie，有时也用其复数形式 Cookies，指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据（通常经过加密）。定义于 RFC2109 和 2965 中的都已废弃，最新取代的规范是 RFC6265 [1]  。（可以叫做浏览器缓存）   session（计算机语言）:在计算">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/05/25/Django之Cookie和Session/"/>





  <title>Django之Cookie和Session | Mr. Lee's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Mr. Lee's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">知识改变命运,技术成就梦想</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/05/25/Django之Cookie和Session/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Mr. Lee">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Mr. Lee's blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Django之Cookie和Session</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-25T22:37:16+08:00">
                2018-05-25
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,119
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h5 id="django中的cookie和session"><a href="#django中的cookie和session" class="headerlink" title="django中的cookie和session"></a>django中的cookie和session</h5><blockquote>
<h6 id="cookie（储存在用户本地终端上的数据）"><a href="#cookie（储存在用户本地终端上的数据）" class="headerlink" title="cookie（储存在用户本地终端上的数据）"></a>cookie（储存在用户本地终端上的数据）</h6><p>Cookie，有时也用其复数形式 <a href="https://baike.baidu.com/item/Cookies/187064" target="_blank" rel="noopener">Cookies</a>，指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据（通常经过加密）。定义于 RFC2109 和 2965 中的都已废弃，最新取代的规范是 RFC6265 [1]<a href=""> </a> 。（可以叫做浏览器缓存）</p>
</blockquote>
<blockquote>
<h6 id="session（计算机语言）"><a href="#session（计算机语言）" class="headerlink" title="session（计算机语言）"></a>session（计算机语言）</h6><p>:在计算机中，尤其是在网络应用中，称为“会话控制”。Session 对象存储特定用户会话所需的属性及配置信息。这样，当用户在应用程序的 Web 页之间跳转时，存储在 Session 对象中的变量将不会丢失，而是在整个用户会话中一直存在下去。当用户请求来自应用程序的 Web 页时，如果该用户还没有会话，则 Web 服务器将自动创建一个 Session 对象。当会话过期或被放弃后，服务器将终止该会话。Session 对象最常见的一个用法就是存储用户的首选项。例如，如果用户指明不喜欢查看图形，就可以将该信息存储在 Session 对象中。有关使用 Session 对象的详细信息，请参阅“ASP 应用程序”部分的“管理会话”。注意 会话状态仅在支持 cookie 的浏览器中保留。</p>
</blockquote>
<h6 id="用户跟踪的三种技术"><a href="#用户跟踪的三种技术" class="headerlink" title="用户跟踪的三种技术"></a>用户跟踪的三种技术</h6><blockquote>
<p>1.cookie   请求头             &lt;最常用&gt;</p>
<p>2.url重写   地址栏</p>
<p>3.隐藏域/隐式表单域   表达提交</p>
</blockquote>
<h6 id="执行表单额外的验证"><a href="#执行表单额外的验证" class="headerlink" title="执行表单额外的验证"></a>执行表单额外的验证</h6><p>方法名必须以clean_开头.这个方法是自动执行的.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">#例如:</span><br><span class="line">class CarRecordForm(forms.ModelForm):</span><br><span class="line">    carno = forms.CharField(min_length=7, max_length=7, label=&apos;车牌号&apos;, 									error_messages=&#123;&apos;carno&apos;: &apos;请输入有效的车牌号&apos;&#125;)</span><br><span class="line">    reason = forms.CharField(max_length=50, label=&apos;违章原因&apos;)</span><br><span class="line">    punish = forms.CharField(max_length=50, required=False, label=&apos;处罚方式&apos;)</span><br><span class="line"></span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    # 执行额外的表单数据验证</span><br><span class="line">    def clean_carno(self):</span><br><span class="line">        _carno = self.cleaned_data[&apos;carno&apos;]</span><br><span class="line">        if not condition:</span><br><span class="line">            raise forms.ValidationError(&apos;...&apos;)</span><br><span class="line">        return _carno</span><br><span class="line">    &quot;&quot;&quot;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>如果是GET请求可以给初始数据.需要使用:initial={} 初始数据没有填写完整</p>
</blockquote>
<h6 id="cookie"><a href="#cookie" class="headerlink" title="cookie"></a>cookie</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">#cookie是保存在浏览器的临时文件中的用户数据(通常是识别用户的ID/token或者是用户的偏好设置).</span><br><span class="line"></span><br><span class="line">#因为在每次请求服务器时在HTTP请求的请求头中都会携带本网站的Cookie数据</span><br><span class="line"></span><br><span class="line">#那么服务器就可以获取这些信息来识别用户的身份或者了解用户的偏好 这就是所谓的用户跟踪</span><br><span class="line"></span><br><span class="line">#因为HTTP本身是无状态的 所有需要使用Cookie/隐藏域/url重写这样的技术实现用户跟踪</span><br><span class="line"></span><br><span class="line">#从请求中读取指定的cookie  — 通过cookie的名字找到对应的值</span><br><span class="line"></span><br><span class="line">#如果请求中没有指定名字的cookie可以通过get方法的第二个参数设置一个默认的返回值</span><br><span class="line"></span><br><span class="line">#当下次请求的时候会通过请求头的时候传给服务器对比.对比上才能登陆.如果任意一边丢失都会重新登陆</span><br></pre></td></tr></table></figure>
<h6 id="session"><a href="#session" class="headerlink" title="session"></a>session</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">#通过request对象的session属性可以获取到session</span><br><span class="line"># session相当于是服务器端用来保存用户数据的一个字典</span><br><span class="line"># session利用了Cookie保存sessionid</span><br><span class="line"># 通过sessionid就可以获取与某个用户对应的会话(也就是用户数据)</span><br><span class="line"># 如果在浏览器中清除了Cookie那么也就清除了sessionid</span><br><span class="line"># 再次访问服务器时服务器会重新分配新的sessionid这也就意味着之前的用户数据无法找回</span><br><span class="line"># 默认情况下Django的session被设定为持久会话而非浏览器续存期会话</span><br><span class="line"># 通过SESSION_EXPIRE_AT_BROWSER_CLOSE和SESSION_COOKIE_AGE参数可以修改默认设定</span><br><span class="line"># Django中的session是进行了持久化处理的因此需要设定session的序列化方式</span><br><span class="line"># 1.6版开始Django默认的session序列化器是JsonSerializer</span><br><span class="line"># 可以通过SESSION_SERIALIZER来设定其他的序列化器(例如PickleSerializer)</span><br><span class="line">(例如:SESSION_SERIALIZER = &apos;django.contrib.sessions.serializers.PickleSerializer&apos;)</span><br></pre></td></tr></table></figure>
<h6 id="项目中的cookie"><a href="#项目中的cookie" class="headerlink" title="项目中的cookie"></a>项目中的cookie</h6><h6 id="项目中的cookie-1"><a href="#项目中的cookie-1" class="headerlink" title="项目中的cookie"></a>项目中的cookie</h6><p>案例:记录用户的上次访问时间</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line">def ajax_search(request):</span><br><span class="line">    current_time = datetime.now().ctime()</span><br><span class="line">    # Cookie是保存在浏览器临时文件中的用户数据(通常是识别用户身份的ID/token或者是用户的偏好设置)</span><br><span class="line">    # 因为每次请求服务器时在HTTP请求的请求头中都会携带本网站的Cookie数据</span><br><span class="line">    # 那么服务器就可以获取这些信息来识别用户身份或者了解用户的偏好 这就是所谓的用户跟踪</span><br><span class="line">    # 因为HTTP本身是无状态的 所以需要使用Cookie/隐藏域/URL重写这样的技术来实现用户跟踪</span><br><span class="line">    # 从请求中读取指定的cookie - 通过cookie的名字找到对应的值</span><br><span class="line">    # 如果请求中没有指定名字的cookie可以通过get方法的第二个参数设置一个默认的返回值</span><br><span class="line">    last_visit_time = request.COOKIES.get(&apos;last_visit_time&apos;)</span><br><span class="line">    if request.method == &apos;GET&apos;:</span><br><span class="line">        response = render(request, &apos;search2.html&apos;,</span><br><span class="line">                          &#123;&apos;last&apos;: last_visit_time if last_visit_time</span><br><span class="line">                           else &apos;你是第一次访问我们的网站&apos;&#125;)</span><br><span class="line">        # 通过render渲染页面后先用set_cookie方法设置cookie后再返回HttpResponse对象</span><br><span class="line">        # 第一个参数是cookie的名字 第二个参数是cookie的值 第三个参数是过期时间(秒)</span><br><span class="line">        response.set_cookie(&apos;last_visit_time&apos;, current_time, max_age=MAX_AGE)</span><br><span class="line">        return response</span><br><span class="line">    else:</span><br><span class="line">        carno = request.POST[&apos;carno&apos;]</span><br><span class="line">        record_list = list(CarRecord.objects.filter(carno__icontains=carno))</span><br><span class="line">        # 第一个参数是要转换成JSON格式(序列化)的对象</span><br><span class="line">        # encoder参数要指定完成自定义对象序列化的编码器(JSONEncoder的子类型)</span><br><span class="line">        # safe参数的值如果为True那么传入的第一个参数只能是字典</span><br><span class="line">        # return HttpResponse(json.dumps(record_list), content_type=&apos;application/json; charset=utf-8&apos;)</span><br><span class="line">        return JsonResponse(record_list, encoder=CarRecordEncoder,</span><br><span class="line">                            safe=False)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def search(request):</span><br><span class="line">    # 请求行中的请求命令</span><br><span class="line">    # print(request.method)</span><br><span class="line">    # 请求行中的路径</span><br><span class="line">    # print(request.path)</span><br><span class="line">    # 请求头(以HTTP_打头的键是HTTP请求的请求头)</span><br><span class="line">    # print(request.META)</span><br><span class="line">    # 查询参数: http://host/path/resource?a=b&amp;c=d</span><br><span class="line">    # print(request.GET)</span><br><span class="line">    # 表单参数</span><br><span class="line">    # print(request.POST)</span><br><span class="line">    if request.method == &apos;GET&apos;:</span><br><span class="line">        ctx = &#123;&apos;show_result&apos;: False&#125;</span><br><span class="line">    else:</span><br><span class="line">        carno = request.POST[&apos;carno&apos;]</span><br><span class="line">        ctx = &#123;</span><br><span class="line">            &apos;show_result&apos;: True,</span><br><span class="line">            &apos;record_list&apos;: list(CarRecord.objects.filter(carno__contains=carno))&#125;</span><br><span class="line">    return render(request, &apos;search.html&apos;, ctx)</span><br></pre></td></tr></table></figure>
<h5 id="Django项目完整步骤"><a href="#Django项目完整步骤" class="headerlink" title="Django项目完整步骤:"></a>Django项目完整步骤:</h5><h6 id="1-建项目"><a href="#1-建项目" class="headerlink" title="1.建项目"></a>1.建项目</h6><h6 id="2-安装pymysql"><a href="#2-安装pymysql" class="headerlink" title="2.安装pymysql"></a>2.安装pymysql</h6><h6 id="3-在项目文件夹下面的init-配置pymysql"><a href="#3-在项目文件夹下面的init-配置pymysql" class="headerlink" title="3.在项目文件夹下面的init 配置pymysql"></a>3.在项目文件夹下面的<strong>init</strong> 配置pymysql</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">在项目文件夹下面的__init__ 配置pymysql</span><br><span class="line">import pymysql</span><br><span class="line">pymysql.install_as_MySQLdb()</span><br></pre></td></tr></table></figure>
<h6 id="4-配置INSTALLED-APPS"><a href="#4-配置INSTALLED-APPS" class="headerlink" title="4.配置INSTALLED_APPS"></a>4.配置INSTALLED_APPS</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">INSTALLED_APPS = [</span><br><span class="line">    &apos;django.contrib.admin&apos;,</span><br><span class="line">    &apos;django.contrib.auth&apos;,</span><br><span class="line">    &apos;django.contrib.contenttypes&apos;,</span><br><span class="line">    &apos;django.contrib.sessions&apos;,</span><br><span class="line">    &apos;django.contrib.messages&apos;,</span><br><span class="line">    &apos;django.contrib.staticfiles&apos;,</span><br><span class="line">    &apos;cart.apps.CartConfig&apos;,</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">中间件 位于浏览器和服务器中间</span><br><span class="line">过滤拦截器</span><br><span class="line">拦截请求和响应</span><br><span class="line">HttpResonse</span><br><span class="line">拦截下来 附加额外的操作</span><br><span class="line">MIDDLEWARE = [</span><br><span class="line">    &apos;django.middleware.security.SecurityMiddleware&apos;,</span><br><span class="line">    &apos;django.contrib.sessions.middleware.SessionMiddleware&apos;,</span><br><span class="line">    &apos;django.middleware.common.CommonMiddleware&apos;,</span><br><span class="line">    &apos;django.middleware.csrf.CsrfViewMiddleware&apos;,</span><br><span class="line">    &apos;django.contrib.auth.middleware.AuthenticationMiddleware&apos;,</span><br><span class="line">    &apos;django.contrib.messages.middleware.MessageMiddleware&apos;,</span><br><span class="line">    &apos;django.middleware.clickjacking.XFrameOptionsMiddleware&apos;,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h6 id="5数据库的配置"><a href="#5数据库的配置" class="headerlink" title="5数据库的配置"></a>5数据库的配置</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">DATABASES = &#123;</span><br><span class="line">    &apos;default&apos;: &#123;</span><br><span class="line">        &apos;ENGINE&apos;: &apos;django.db.backends.mysql&apos;,</span><br><span class="line">        &apos;NAME&apos;: &apos;shop&apos;,</span><br><span class="line">        &apos;HOST&apos;:&apos;127.0.0.1&apos;,</span><br><span class="line">        &apos;POST&apos;:&apos;3306&apos;,</span><br><span class="line">        &apos;USER&apos;:&apos;root&apos;,</span><br><span class="line">        &apos;PASSWORD&apos;:&apos;123456&apos;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h6 id="6配置静态资源"><a href="#6配置静态资源" class="headerlink" title="6配置静态资源"></a>6配置静态资源</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">STATICFILES_DIRS = [os.path.join(BASE_DIR,&apos;static&apos;),]</span><br><span class="line">STATIC_URL = &apos;/static/&apos;</span><br></pre></td></tr></table></figure>
<h6 id="7配置时区-语言"><a href="#7配置时区-语言" class="headerlink" title="7配置时区/语言"></a>7配置时区/语言</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">LANGUAGE_CODE = &apos;zh-hans&apos;</span><br><span class="line"></span><br><span class="line">TIME_ZONE = &apos;Asia/Chongqing&apos;</span><br></pre></td></tr></table></figure>
<h6 id="8配置url"><a href="#8配置url" class="headerlink" title="8配置url"></a>8配置url</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">from cart import views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(&apos;&apos;,views.index),</span><br><span class="line">    path(&apos;add_to_cart/&lt;int:id&gt;&apos;,views.add_to_cart),</span><br><span class="line">    path(&apos;show_cart&apos;,views.show_cart),</span><br><span class="line">    path(&apos;admin/&apos;, admin.site.urls),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h6 id="9写视图"><a href="#9写视图" class="headerlink" title="9写视图"></a>9写视图</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">from django.shortcuts import render</span><br><span class="line"></span><br><span class="line">def index(request):</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def add_to_cart(request):</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line">def show_cart(request):</span><br><span class="line">    pass</span><br></pre></td></tr></table></figure>
<h6 id="10-建立models"><a href="#10-建立models" class="headerlink" title="10 建立models"></a>10 建立models</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">from django.db import models</span><br><span class="line"></span><br><span class="line">class Goods(models.Model):</span><br><span class="line">    &quot;&quot;&quot;商品模型类&quot;&quot;&quot;</span><br><span class="line">    id = models.AutoField(primary_key=True,db_column=&apos;gid&apos;)</span><br><span class="line">    name = models.CharField(max_length=50,db_column=&apos;gname&apos;)</span><br><span class="line">    price = models.DecimalField(max_digits=10,decimal_places=2,db_column=&apos;gprice&apos;)</span><br><span class="line">    image = models.CharField(max_length=255,db_column=&apos;gimage&apos;)</span><br><span class="line">    class Meta:</span><br><span class="line"></span><br><span class="line">        db_table = &apos;tb_goods&apos;</span><br><span class="line">        ordering = (&apos;id&apos;,)</span><br></pre></td></tr></table></figure>
<h6 id="11迁移"><a href="#11迁移" class="headerlink" title="11迁移"></a>11迁移</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">python manage.py makemigrations cart   </span><br><span class="line">python manage.py migrate</span><br></pre></td></tr></table></figure>
<h6 id="12注册后台管理员账户"><a href="#12注册后台管理员账户" class="headerlink" title="12注册后台管理员账户"></a>12注册后台管理员账户</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">例如:</span><br><span class="line">from django.contrib import admin</span><br><span class="line"></span><br><span class="line">from cart.models import Goods</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class GoodsAdmin(admin.ModelAdmin):</span><br><span class="line">    list_display = (&apos;id&apos;,&apos;name&apos;,&apos;price&apos;,&apos;image&apos;)</span><br><span class="line">    search_fields = (&apos;name&apos;,)</span><br><span class="line">    </span><br><span class="line">admin.site.register(Goods,GoodsAdmin)</span><br></pre></td></tr></table></figure>
<h6 id="13-GUANLIY"><a href="#13-GUANLIY" class="headerlink" title="13:GUANLIY"></a>13:GUANLIY</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">(venv) lizhonglindeMacBook-Pro:shop lizhonglin$ python manage.py createsuperuser </span><br><span class="line">Username (leave blank to use &apos;lizhonglin&apos;): admin</span><br><span class="line">Email address: admin@126.com</span><br><span class="line">Password: </span><br><span class="line">Password (again): </span><br><span class="line">Superuser created successfully.</span><br><span class="line">(venv) lizhonglindeMacBook-Pro:shop lizhonglin$</span><br></pre></td></tr></table></figure>
<h6 id="14进入管理员界面查看数据"><a href="#14进入管理员界面查看数据" class="headerlink" title="14进入管理员界面查看数据"></a>14进入管理员界面查看数据</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">可以插入数据</span><br></pre></td></tr></table></figure>
<h6 id="15配置url"><a href="#15配置url" class="headerlink" title="15配置url"></a>15配置url</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">配置首页</span><br><span class="line">def index(request):</span><br><span class="line">    good_list = list(Goods.objects.all())</span><br><span class="line">    return render(request,&apos;goods.html&apos;,&#123;&apos;goods_list&apos;:good_list&#125;)</span><br></pre></td></tr></table></figure>
<h6 id="16开始在视图中定制自己的功能"><a href="#16开始在视图中定制自己的功能" class="headerlink" title="16开始在视图中定制自己的功能"></a>16开始在视图中定制自己的功能</h6>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/WechatIMG26.jpeg" alt="Mr. Lee 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">
            -------------本文结束
            <i class="fa fa-paw"></i>
            感谢您的阅读-------------
        </div>
    
</div>
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/cookie与session/" rel="tag"><i class="fa fa-tag"></i> cookie与session</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/05/25/Web框架Django-一/" rel="next" title="Web框架Django(一)">
                <i class="fa fa-chevron-left"></i> Web框架Django(一)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/06/03/最适合初学Django框架的项目/" rel="prev" title="最适合初学Django框架的项目">
                最适合初学Django框架的项目 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/avatar.png"
                alt="Mr. Lee" />
            
              <p class="site-author-name" itemprop="name">Mr. Lee</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/Leezhonglin" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:380604322@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>

              <ul class="links-of-blogroll-list">

                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="https://my.csdn.net/jackfrued/" title="大 神" target="_blank">
                        大 神
                      </a>
                    </span>
                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="https://blog.csdn.net/qq_33196814" title="CSDN" target="_blank">
                        CSDN
                      </a>
                    </span>
                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="http://www.python.org" title="python" target="_blank">
                        python
                      </a>
                    </span>
                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="http://redisdoc.com/" title="redis" target="_blank">
                        redis
                      </a>
                    </span>
                

              </ul>


            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-5"><a class="nav-link" href="#django中的cookie和session"><span class="nav-number">1.</span> <span class="nav-text">django中的cookie和session</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#cookie（储存在用户本地终端上的数据）"><span class="nav-number">1.1.</span> <span class="nav-text">cookie（储存在用户本地终端上的数据）</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#session（计算机语言）"><span class="nav-number">1.2.</span> <span class="nav-text">session（计算机语言）</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#用户跟踪的三种技术"><span class="nav-number">1.3.</span> <span class="nav-text">用户跟踪的三种技术</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#执行表单额外的验证"><span class="nav-number">1.4.</span> <span class="nav-text">执行表单额外的验证</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#cookie"><span class="nav-number">1.5.</span> <span class="nav-text">cookie</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#session"><span class="nav-number">1.6.</span> <span class="nav-text">session</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#项目中的cookie"><span class="nav-number">1.7.</span> <span class="nav-text">项目中的cookie</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#项目中的cookie-1"><span class="nav-number">1.8.</span> <span class="nav-text">项目中的cookie</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Django项目完整步骤"><span class="nav-number">2.</span> <span class="nav-text">Django项目完整步骤:</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#1-建项目"><span class="nav-number">2.1.</span> <span class="nav-text">1.建项目</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#2-安装pymysql"><span class="nav-number">2.2.</span> <span class="nav-text">2.安装pymysql</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#3-在项目文件夹下面的init-配置pymysql"><span class="nav-number">2.3.</span> <span class="nav-text">3.在项目文件夹下面的init 配置pymysql</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#4-配置INSTALLED-APPS"><span class="nav-number">2.4.</span> <span class="nav-text">4.配置INSTALLED_APPS</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#5数据库的配置"><span class="nav-number">2.5.</span> <span class="nav-text">5数据库的配置</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#6配置静态资源"><span class="nav-number">2.6.</span> <span class="nav-text">6配置静态资源</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#7配置时区-语言"><span class="nav-number">2.7.</span> <span class="nav-text">7配置时区/语言</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#8配置url"><span class="nav-number">2.8.</span> <span class="nav-text">8配置url</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#9写视图"><span class="nav-number">2.9.</span> <span class="nav-text">9写视图</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#10-建立models"><span class="nav-number">2.10.</span> <span class="nav-text">10 建立models</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#11迁移"><span class="nav-number">2.11.</span> <span class="nav-text">11迁移</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#12注册后台管理员账户"><span class="nav-number">2.12.</span> <span class="nav-text">12注册后台管理员账户</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#13-GUANLIY"><span class="nav-number">2.13.</span> <span class="nav-text">13:GUANLIY</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#14进入管理员界面查看数据"><span class="nav-number">2.14.</span> <span class="nav-text">14进入管理员界面查看数据</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#15配置url"><span class="nav-number">2.15.</span> <span class="nav-text">15配置url</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#16开始在视图中定制自己的功能"><span class="nav-number">2.16.</span> <span class="nav-text">16开始在视图中定制自己的功能</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Mr. Lee</span>

  
</div>


  <span class="post-meta-divider">|</span>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://github.com/Leezhonglin">Leezhonglin</a> 提供技术支持</div>



  <span class="post-meta-divider">|</span>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>


  <span class="post-meta-divider">|</span>


<span id="busuanzi_container_site_pv">
    本站总访问量:<span id="busuanzi_value_site_pv"></span>次
</span>


  <span class="post-meta-divider">|</span>


</div>


<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共:64.5k字</span>
</div>


  <span class="post-meta-divider">|</span>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
